package atomic.atomicUpdater;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * @author ZhuQi
 * @ClassName AtomicReferenceFeildUpdaterDemo
 * @Date 2022/9/16 13:54
 * @Version 1.0
 * @Description 测试 AtomicReferenceFieldUpdater
 */
@Slf4j
public class AtomicReferenceFieldUpdaterDemo {

    /**
     * 张三有 55块遗产每个银行都想存，这里测试 修改 张三账号银行的名称
     * @param args
     */
    @SneakyThrows
    public static void main(String[] args) {
        Resource resource = new Resource();
        AtomicReferenceFieldUpdater<Resource, String> referenceFieldUpdater
                = AtomicReferenceFieldUpdater.newUpdater(Resource.class, String.class, "bank");
        CountDownLatch countDownLatch = new CountDownLatch(2);

        new Thread(()->{
            boolean icbc = referenceFieldUpdater.compareAndSet(resource, null, "ICBC");
            log.info("银行{} 修改结果:{}", "icbc" , icbc);
            countDownLatch.countDown();
        },"thread1").start();
        new Thread(()->{
            boolean bcbc = referenceFieldUpdater.compareAndSet(resource, null, "BCBC");
            log.info("银行{} 修改结果:{}", "BCBC" , bcbc);
            countDownLatch.countDown();
            countDownLatch.countDown();
        },"thread2").start();

        countDownLatch.await();
        log.info("rsource:{}", resource);
    }
}
@Data
@NoArgsConstructor
@AllArgsConstructor
class Resource{
    private String name = "张三";
    public volatile String bank;
    private BigDecimal money = new BigDecimal("55.55");
}